package cn.gong.movie.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import cn.gong.movie.bean.Movie;
import cn.gong.movie.ui.R;
import framework.base.BaseAdap;
import framework.jiekou.MoreView;

public abstract class AdapMovie extends BaseAdap {
	private List<Movie> movies;
	private MoreView more;

	public AdapMovie(MoreView more) {
		this.more = more;
	}

	@Override
	public int getCount() {
		return movies != null ? movies.size() + 1 : 1;
	}

	@Override
	public Object getItem(int position) {
		return (position == (getCount() - 1)) ? null : movies.get(position);

	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (position == getCount() - 1) {
			return more.moreView();
		}

		if (convertView == null || convertView.findViewById(R.id.movie_item_tv_name) == null) {
			convertView = inflate(R.layout.movie_item);
		}

		Movie movie = movies.get(position);

		// name
		TextView nameTv = findTextViewById(R.id.movie_item_tv_name, convertView);
		setText(nameTv, movie.getName());

		// date
		TextView dateTv = findTextViewById(R.id.movie_item_tv_date, convertView);
		setText(dateTv, formatDate(movie.getDate()));

		return convertView;
	}

	private String formatDate(String date) {
		try {
			return new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(date));
		} catch (ParseException e) {
			return date;
		}
	}

	public void setList(List<Movie> movies) {
		this.movies = movies;
		notifyDataSetChanged();
	}

	public void addList(List<Movie> movies) {
		if (movies != null && movies.size() > 0) {
			if (this.movies != null) {
				this.movies.addAll(movies);
			} else {
				this.movies = movies;
			}
		}
		notifyDataSetChanged();
	}

	public void addListFirst(Movie movie) {
		if (movie != null) {
			if (this.movies != null) {
				this.movies.add(0, movie);
			} else {
				this.movies = new ArrayList<Movie>();
				this.movies.add(movie);
			}
		}
		notifyDataSetChanged();
	}

	public void deleteMovie(Movie oprateMovie) {
		if (oprateMovie != null) {
			this.movies.remove(oprateMovie);
			notifyDataSetChanged();
		}
	}
}
